import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, Popconfirm, Space, Table, Tag, message } from 'antd';
import {
  deleteApiRole as Delete,
  postApiRoleByIndexByLimitPagedList as PagedList,
  getApiRoleDetailById as GetDetail,
  getApiRoleConfigreById as GetConfigre,
  getApiRoleByIdUsers as GetAuthorizeUsers,
} from '@/services/furion-cms/role'
import React, { useRef, useState } from 'react';

import DetailViewer from './components/roleDetail';
import RoleConfigure from './components/roleConfigure'; import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import { useIntl } from 'umi';
import RoleAuthorize from './components/roleAuthorize';
import PermissionsDefinition from '@/permissionsDefinition';
import { useCustomAccess } from '@/components/CustomAccess';

const RoleManager: React.FC = () => {
  const actionRef = useRef<ActionType>();
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const AccessButton = useCustomAccess(Button);
  const AccessConfirm = useCustomAccess(Popconfirm);

  const [details, setDetails] = useState<API.RoleDetailDto | API.RoleConfigureDetailDto>();
  const [detailModalVisible, handelDetailModalVisible] = useState(false);

  const [configureModalVisible, handleConfigureModalVisible] = useState(false);
  const [loadingVisible, handelLoadingVisible] = useState(false);

  const [authorize, setAuthorize] = useState<Partial<API.RoleDto & { users?: number[] }>>();
  const [authorizeModalVisible, handleAuthorizeModalVisible] = useState(false);

  const getDetail = async (id: number) => {
    handelLoadingVisible(true);
    try {
      const { data } = await GetDetail({ id });
      setDetails(data);
      handelDetailModalVisible(true);
    } catch { }
    handelLoadingVisible(false);
  }

  const getConfigre = async (id: number) => {
    handelLoadingVisible(true);
    try {
      const { data } = await GetConfigre({ id });
      setDetails(data);
      handleConfigureModalVisible(true);
    } catch { }
    handelLoadingVisible(false);
  }

  const getAuthorize = async (row: API.RoleDto) => {
    handelLoadingVisible(true);
    try {
      const { data } = await GetAuthorizeUsers({ id: row.id ?? 0 });
      setAuthorize({
        ...row,
        users: data?.map(m => m.id ?? 0) ?? []
      })
      handleAuthorizeModalVisible(true);
    } catch { }

    handelLoadingVisible(false);
  }

  const handleDeleteConfirm = async (idList: any[]) => {
    handelLoadingVisible(true);
    try {
      await Delete(idList);
      message.success('删除操作成功');
      actionRef.current?.reload();
    } catch (error) { }
    handelLoadingVisible(false);
  }

  const columns: ProColumns<API.RoleDto>[] = [
    {
      title: intl.formatMessage({
        id: 'pages.role.name',
        defaultMessage: '名称'
      }),
      dataIndex: 'name',
      search: false,
      render: (_, entity) => {
        return <Space>
          <span>{entity.name}</span>
          {entity.hasSeed && <Tag color="magenta">{intl.formatMessage({ id: "pages.role.type.inner", defaultMessage: "内置" })}</Tag>}
          {entity.isDefault && <Tag color="blue">{intl.formatMessage({ id: "pages.role.type.default", defaultMessage: "默认" })}</Tag>}
        </Space>;
      }
    },
    {
      title: intl.formatMessage({
        id: 'pages.role.description',
        defaultMessage: '描述'
      }),
      dataIndex: 'description',
      search: false,
    },
    {
      title: intl.formatMessage({
        id: 'pages.role.createdTime',
        defaultMessage: '创建时间'
      }),
      dataIndex: 'createdTime',
      valueType: 'dateRange',
      sorter: true,
      width: 180,
      render: (dom, entity) => {
        return entity.createdTime;
      }
    },
    {
      title: intl.formatMessage({
        id: 'pages.searchTable.titleOption',
        defaultMessage: '操作'
      }),
      dataIndex: 'option',
      valueType: 'option',
      width: 250,
      render: (_, record) => [
        <AccessButton key="update"
          code={PermissionsDefinition.Role.UpdateRole}
          disabled={record.hasSeed} type="link" size="small"
          onClick={() => getDetail(record.id!)}>
          {intl.formatMessage({
            id: 'pages.common.update',
            defaultMessage: '编辑'
          })}
        </AccessButton>,
        <AccessButton key="configure"
          code={PermissionsDefinition.Role.ConfigureRole}
          disabled={record.hasSeed} type="link" size="small"
          onClick={() => getConfigre(record.id!)}>
          {intl.formatMessage({
            id: 'pages.role.configure',
            defaultMessage: '配置'
          })}
        </AccessButton>,
        <AccessButton key="authorize"
          code={PermissionsDefinition.Role.AuthorizeRole}
          type="link" size="small"
          onClick={() => getAuthorize(record)}>
          {intl.formatMessage({
            id: 'pages.role.authorize',
            defaultMessage: '授权'
          })}
        </AccessButton>,
        <AccessConfirm key="delete"
          code={PermissionsDefinition.Role.DeleteRole}
          disabled={record.hasSeed}
          title={intl.formatMessage({
            id: 'pages.common.delete.confirm',
            defaultMessage: '您是否确认将「{name}」删除?'
          }, {
            name: record.name
          })}
          okText={intl.formatMessage({
            id: 'pages.common.confirm.ok',
            defaultMessage: '确认',
          })}
          cancelText={intl.formatMessage({
            id: 'pages.common.confirm.cancel',
            defaultMessage: '取消',
          })}
          onConfirm={() => handleDeleteConfirm([record.id!])}
        >
          <Button disabled={record.hasSeed} type="link" size="small"
          >{intl.formatMessage({
            id: 'pages.common.delete',
            defaultMessage: '删除'
          })}</Button>
        </AccessConfirm>
      ],
    },
  ];

  return (
    <PageContainer className={styles.main}
      breadcrumbRender={false}>
      <ProTable<API.RoleDto>
        actionRef={actionRef}
        loading={loadingVisible}
        rowKey="id"
        search={{ filterType: "light" }}
        pagination={{
          pageSize: 10,
          showSizeChanger:true
        }}
        options={{
          search: true,
        }}
        request={(params, sort, filter) => {
          handelLoadingVisible(true);
          // 表单搜索项会从 params 传入，传递给后端接口。
          console.log(params, sort, filter);
          // 转换固定的参数
          const { current, pageSize, createdTime } = params;
          const [StartTime, EndTime] = createdTime || [];
          // 删除无效参数
          delete params.current;
          delete params.pageSize;
          delete params.createdTime;
          // 发起请求
          return PagedList({
            index: (current || 1),
            limit: (pageSize || 10),
            StartTime,
            EndTime,
            ...params
          }, sort).then(result => {
            const { list: data, total } = result.data || {};
            return {
              data,
              success: result.success,
              total
            }
          }).finally(() => handelLoadingVisible(false));
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
        }}
        columns={columns}
        toolBarRender={() => [
          <AccessButton type="primary"
            code={PermissionsDefinition.Role.CreateRole}
            key="create"
            onClick={() => {
              setDetails(undefined);
              handelDetailModalVisible(true);
            }}>
            {intl.formatMessage({
              id: 'pages.role.create',
              defaultMessage: '创建角色'
            })}
          </AccessButton>,
        ]}
        tableAlertOptionRender={({ selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={16}>
              <AccessConfirm key="batchDelete"
                code={PermissionsDefinition.Role.DeleteRole}
                title={intl.formatMessage({
                  id: 'pages.common.batchDeletion.confirm',
                  defaultMessage: '您是否确认删除选中的「{count}」项数据?'
                }, { count: selectedRowKeys.length })}
                onConfirm={() => {
                  handleDeleteConfirm(selectedRowKeys);
                  onCleanSelected();
                }}
              >
                <a href="#">{intl.formatMessage({
                  id: 'pages.common.batchDeletion',
                  defaultMessage: '批量删除'
                })}</a>
              </AccessConfirm>
            </Space>
          );
        }}
      />
      <DetailViewer
        onVisibleChange={handelDetailModalVisible}
        modalVisible={detailModalVisible}
        recored={details}
        onUpdate={() => actionRef.current?.reload()}
      />
      <RoleConfigure
        onVisibleChange={handleConfigureModalVisible}
        modalVisible={configureModalVisible}
        recored={details}
        modalProps={{
          closable: false
        }}
      />
      <RoleAuthorize
        onVisibleChange={handleAuthorizeModalVisible}
        modalVisible={authorizeModalVisible}
        recored={authorize}
        modalProps={{
          closable: false
        }}
      />
    </PageContainer>
  )
};

export default RoleManager;
